/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-18 10:33:14
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-04-18 10:42:35
 */
'use strict';
/*
if you open the initializer feature, please implement the initializer function, as below:
module.exports.initializer = function(context, callback) {
  console.log('initializing');
  callback(null, ''); 
};
*/
const getRawBody = require('raw-body');
const port = 3000;
const Koa = require('koa2')
const route = require('koa-route')
const websockify = require('koa-websocket')
const app = websockify(new Koa());
app.ws.use(function (ctx, next) {
  ctx.websocket.send("连接成功");
  return next(ctx)
})
app.ws.use(route.all('/', function (ctx) {
  /**接收消息*/
  ctx.websocket.on('message', function (message) {
    console.log(message);
    // 返回给前端的数据
    let data = JSON.stringify({
      id: Math.ceil(Math.random() * 1000),
      time: parseInt(new Date() / 1000)
    })
    ctx.websocket.send(data);
  })
}));

app.listen(port, () => {
  console.log("localhost:" + port);
});

module.exports.handler = function (req, resp, context) {
  getRawBody(req, async (err, body) => {
    if (body) {

      await sendResp({
        data: "未查询到数据"
      })
    } else {
      await sendResp({
        data: "请传入数据"
      })
    }
  });

  // 返回
  sendResp = (data) => {
    resp.setHeader('content-type', 'application/json');
    try {
      resp.send(JSON.stringify({
        success: true,
        data: data
      }));
    }
    catch (err) {
      resp.send(JSON.stringify({
        success: false,
        data: err.message
      }));
    }
  }

}